package com.codesuc.aichat.user.controller;

import com.codesuc.aichat.common.Result;
import com.codesuc.aichat.interceptor.LoginInterceptor;
import com.codesuc.aichat.user.entity.User;
import com.codesuc.aichat.user.service.UserService;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.Map;

/**
 * @Author: ZhangGongMing
 * @CreateTime: 2025/09/23 12:56
 * @Description: User控制层
 * @Version: 1.0
 */
@RestController
@RequestMapping(value = "/api/v1/user")
@Tag(name = "UserController", description = "User控制层")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Result<?> register(@RequestBody User user) {
        return userService.register(user);
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<Map<String, Object>> login(@RequestBody User user) {
        return userService.login(user);
    }

    @GetMapping("/info")
    @Operation(summary = "获取当前用户信息")
    public Result<LoginInterceptor.LoginUser> getUserInfo() {
        // 检查用户是否已登录
        if (!StpUtil.isLogin()) {
            return Result.error("未能读取到有效token");
        }
        
        // 获取登录用户ID
        long userId = StpUtil.getLoginIdAsLong();

        User user = userService.getById(userId);
        // 构建登录用户信息
        LoginInterceptor.LoginUser loginUser = LoginInterceptor.LoginUser.builder()
                .mail(user.getEmail())
                .nickname(user.getUsername())
                .username(user.getUsername())
                .id(userId)
                .build();
                
        return Result.ok(loginUser);
    }

    @PostMapping("/logout")
    @Operation(summary = "用户退出登录")
    public Result<?> logout() {
        StpUtil.logout();
        return Result.ok("退出成功");
    }
}
